package com.jiangdg.usbcamera.view;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.hardware.usb.UsbDevice;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;

import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jiangdg.usbcamera.R;
import com.jiangdg.usbcamera.UVCCameraHelper;
import com.jiangdg.usbcamera.application.MyApplication;
import com.jiangdg.usbcamera.login.LoginActivity;
import com.jiangdg.usbcamera.login.LoginInfo;
import com.jiangdg.usbcamera.url.UrlContext;
import com.jiangdg.usbcamera.utils.FileUtils;
import com.jiangdg.usbcamera.utils.HttpUtils;
import com.jiangdg.usbcamera.utils.SPUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.Size;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.common.AbstractUVCCameraHandler;
import com.serenegiant.usb.encoder.RecordParams;
import com.serenegiant.usb.widget.CameraViewInterface;
import com.wlf.mediapick.MediaPicker;
import com.wlf.mediapick.entity.MediaEntity;
import com.wlf.mediapick.entity.MediaPickConstants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.ByteArrayEntity;
import cz.msebera.android.httpclient.message.BasicHeader;
import cz.msebera.android.httpclient.protocol.HTTP;

/**
 * UVCCamera use demo
 * <p>
 * Created by jiangdongguo on 2017/9/30.
 */

public class USBCameraActivity extends AppCompatActivity implements CameraDialog.CameraDialogParent, CameraViewInterface.Callback {
    private static final String TAG = "Debug";
    @BindView(R.id.tv_yisheng)
    TextView tvYisheng;
    @BindView(R.id.ll_infor)
    LinearLayout llInfor;
    @BindView(R.id.btn_user)
    Button btnUser;

    @BindView(R.id.btn_yes)
    Button btnYes;
    @BindView(R.id.btn_logout)
    Button btnLogout;
    @BindView(R.id.llayout_contrast)
    LinearLayout llayoutContrast;
    @BindView(R.id.llayout_brightness)
    LinearLayout llayoutBrightness;
    @BindView(R.id.et_newName)
    EditText etNewName;
    @BindView(R.id.et_newCode)
    EditText etNewCode;
    @BindView(R.id.et_newPhone)
    EditText etNewPhone;
    @BindView(R.id.ll_add)
    LinearLayout llAdd;
    @BindView(R.id.tv_xingbie)
    TextView tvXingbie;
    @BindView(R.id.btn_newPersion)
    Button btnNewPersion;
    @BindView(R.id.et_phone)
    EditText etPhone;
    private ArrayList<String> images = new ArrayList<>(); //要提交的图片id
    private ArrayList<String> arrayList = new ArrayList<>(); //要提交的图片id
    Context context;
    @BindView(R.id.camera_view)
    public View mTextureView;
    @BindView(R.id.toolbar)
    public Toolbar mToolbar;
    @BindView(R.id.seekbar_brightness)
    public SeekBar mSeekBrightness;
    @BindView(R.id.seekbar_contrast)
    public SeekBar mSeekContrast;
    @BindView(R.id.switch_rec_voice)
    public Switch mSwitchVoice;
    @BindView(R.id.tv_huanzhe)
    TextView huanzhe;
    @BindView(R.id.tv_age)
    TextView age;
    @BindView(R.id.tv_phone)
    TextView tvphone;
    private String persionID;
    AllInfo allinfo;
    private UVCCameraHelper mCameraHelper;
    private CameraViewInterface mUVCCameraView;
    private AlertDialog mDialog;

    private boolean isRequest;
    private boolean isPreview;
    private String button_status = "0"; //按钮状态 0 ->抬起       1->按下
    private long update_time = 0; //按钮状态更新时间
    private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {

        @Override
        public void onAttachDev(UsbDevice device) {
            // request open permission
            if (!isRequest) {
                isRequest = true;
                if (mCameraHelper != null) {
                    mCameraHelper.requestPermission(0);
                }
            }
        }

        @Override
        public void onDettachDev(UsbDevice device) {
            // close camera
            if (isRequest) {
                isRequest = false;
                mCameraHelper.closeCamera();
                showShortMsg(device.getDeviceName() + " is out");
            }
        }

        @Override
        public void onConnectDev(UsbDevice device, boolean isConnected) {
            if (!isConnected) {
                showShortMsg("fail to connect,please check resolution params");
                isPreview = false;
            } else {
                isPreview = true;
                showShortMsg("connecting");
                // initialize seekbar
                // need to wait UVCCamera initialize over
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Looper.prepare();
                        if (mCameraHelper != null && mCameraHelper.isCameraOpened()) {
                            mSeekBrightness.setProgress(mCameraHelper.getModelValue(UVCCameraHelper.MODE_BRIGHTNESS));
                            mSeekContrast.setProgress(mCameraHelper.getModelValue(UVCCameraHelper.MODE_CONTRAST));
                        }
                        Looper.loop();
                    }
                }).start();
            }
        }

        @Override
        public void onDisConnectDev(UsbDevice device) {
            showShortMsg("disconnecting");

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbcamera);
        ButterKnife.bind(this);
        context = this;
        initView();

        // step.1 initialize UVCCameraHelper
        mUVCCameraView = (CameraViewInterface) mTextureView;
        mUVCCameraView.setCallback(this);
        mCameraHelper = UVCCameraHelper.getInstance();
        mCameraHelper.setDefaultFrameFormat(UVCCameraHelper.FRAME_FORMAT_MJPEG);
        mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);

        mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {
            @Override
            public void onPreviewResult(byte[] nv21Yuv) {
                Log.d(TAG, "onPreviewResult: " + nv21Yuv.length);
            }
        });

        allinfo = new AllInfo();
    }

    private void initView() {
        setSupportActionBar(mToolbar);

        mSeekBrightness.setMax(100);
        mSeekBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mCameraHelper != null && mCameraHelper.isCameraOpened()) {
                    mCameraHelper.setModelValue(UVCCameraHelper.MODE_BRIGHTNESS, progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mSeekContrast.setMax(100);
        mSeekContrast.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mCameraHelper != null && mCameraHelper.isCameraOpened()) {
                    mCameraHelper.setModelValue(UVCCameraHelper.MODE_CONTRAST, progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


        LiveEventBus
                .get("camera_button", String.class)
                .observe(this, new Observer<String>() {
                    @Override
                    public void onChanged(@Nullable String s) {   //拍照消息0   开始录像 消息1   关闭录像 消息2
//                        Toast.makeText(context,"按钮状态变化"+s,Toast.LENGTH_SHORT ).show();
                        if ("0".equals(s)) { //拍照
                            takePhoto();
                        } else if ("1".equals(s)) { //开始录像
                            startRecordMovie();
                        } else if ("2".equals(s)) {//结束录制
                            stopRecordMovie();

                        }
                    }
                });
        String user = (String) SPUtils.get(USBCameraActivity.this, "userInfo", "");
        Gson gson = new Gson();
        LoginInfo info = gson.fromJson(user.toString(), LoginInfo.class);
        tvYisheng.setText("医生:" + info.getUserinfo().getName());
    }

    @Override
    protected void onStart() {
        super.onStart();
        // step.2 register USB event broadcast
//        if (mCameraHelper != null) {
//            mCameraHelper.registerUSB();
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // step.2 register USB event broadcast
        if (mCameraHelper != null) {
            mCameraHelper.registerUSB();

//            if ( !mCameraHelper.isCameraOpened()) {
//                showShortMsg("sorry,camera open failed");
//                return;
//            }
//            mCameraHelper.updateResolution(640, 480);

        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // step.3 unregister USB event broadcast
        if (mCameraHelper != null) {
            mCameraHelper.unregisterUSB();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_toobar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_takepic:   //照相
                if (takePhoto()) return super.onOptionsItemSelected(item);
                break;
//            case R.id.menu_recording:  //
//                if (recordMovie()) return super.onOptionsItemSelected(item);
//                break;
            case R.id.menu_resolution:  //
                if (mCameraHelper == null || !mCameraHelper.isCameraOpened()) {
                    showShortMsg("sorry,camera open failed");
                    return super.onOptionsItemSelected(item);
                }
                showResolutionListDialog();
                break;
            case R.id.menu_focus:  //对焦
                if (mCameraHelper == null || !mCameraHelper.isCameraOpened()) {
                    showShortMsg("sorry,camera open failed");
                    return super.onOptionsItemSelected(item);
                }
                mCameraHelper.startCameraFoucs();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /*
    开始记录视屏
     */
    private boolean startRecordMovie() {
        if (mCameraHelper == null || !mCameraHelper.isCameraOpened()) {
            showShortMsg("sorry,camera open failed");
            return true;
        }
        if (true) {  //判断是否已经开始摄像
            String videoPath = UVCCameraHelper.ROOT_PATH + MyApplication.DIRECTORY_NAME + "/videos/" + System.currentTimeMillis();

//                    FileUtils.createfile(FileUtils.ROOT_PATH + "test666.h264");
            // if you want to record,please create RecordParams like this
            RecordParams params = new RecordParams();
            params.setRecordPath(videoPath);
            params.setRecordDuration(0);                        // auto divide saved,default 0 means not divided
            params.setVoiceClose(true);    // is close voice  关闭声音录制

            params.setSupportOverlay(true); // overlay only support armeabi-v7a & arm64-v8a
            mCameraHelper.startPusher(params, new AbstractUVCCameraHandler.OnEncodeResultListener() {
                @Override
                public void onEncodeResult(byte[] data, int offset, int length, long timestamp, int type) {
                    // type = 1,h264 video stream
                    if (type == 1) {
                        FileUtils.putFileStream(data, offset, length);
                    }
                    // type = 0,aac audio stream
                    if (type == 0) {

                    }
                }

                @Override
                public void onRecordResult(String videoPath) {
                    if (TextUtils.isEmpty(videoPath)) {
                        return;
                    }
//                    postToServer(videoPath);

                    allinfo.images.add(videoPath);
                }
            });
            // if you only want to push stream,please call like this
            // mCameraHelper.startPusher(listener);
            showShortMsg("开始录制...");
            mSwitchVoice.setEnabled(false);
        } else {
            FileUtils.releaseFile();
            mCameraHelper.stopPusher();
            showShortMsg("stop record...");
            mSwitchVoice.setEnabled(true);
        }
        return false;
    }

    /*
        结束记录视屏
         */
    private boolean stopRecordMovie() {
        if (mCameraHelper == null || !mCameraHelper.isCameraOpened()) {
            showShortMsg("sorry,camera open failed");
            return true;
        }
        if (false) {  //判断是否已经开始摄像
            String videoPath = UVCCameraHelper.ROOT_PATH + MyApplication.DIRECTORY_NAME + "/videos/" + System.currentTimeMillis()
                    + UVCCameraHelper.SUFFIX_MP4;

//                    FileUtils.createfile(FileUtils.ROOT_PATH + "test666.h264");
            // if you want to record,please create RecordParams like this
            RecordParams params = new RecordParams();
            params.setRecordPath(videoPath);
            params.setRecordDuration(0);                        // auto divide saved,default 0 means not divided
            params.setVoiceClose(true);    // is close voice  关闭声音录制

            params.setSupportOverlay(true); // overlay only support armeabi-v7a & arm64-v8a
            mCameraHelper.startPusher(params, new AbstractUVCCameraHandler.OnEncodeResultListener() {
                @Override
                public void onEncodeResult(byte[] data, int offset, int length, long timestamp, int type) {
                    // type = 1,h264 video stream
                    if (type == 1) {
                        FileUtils.putFileStream(data, offset, length);
                    }
                    // type = 0,aac audio stream
                    if (type == 0) {

                    }
                }

                @Override
                public void onRecordResult(String videoPath) {
                    if (TextUtils.isEmpty(videoPath)) {
                        return;
                    }

//                    postToServer(videoPath);
//                    new Handler(getMainLooper()).post(() -> Toast.makeText(USBCameraActivity.this, "save videoPath:"+videoPath, Toast.LENGTH_SHORT).show());
                }
            });
            // if you only want to push stream,please call like this
            // mCameraHelper.startPusher(listener);
            showShortMsg("开始录制...");
            mSwitchVoice.setEnabled(false);
        } else {
            FileUtils.releaseFile();
            mCameraHelper.stopPusher();
            showShortMsg("结束录制...");
            mSwitchVoice.setEnabled(true);
        }
        return false;
    }

    /*
    拍照 上传照片
     */
    private boolean takePhoto() {
        if (mCameraHelper == null || !mCameraHelper.isCameraOpened()) {
            showShortMsg("sorry,camera open failed");
            return true;
        }
        String picPath = UVCCameraHelper.ROOT_PATH + MyApplication.DIRECTORY_NAME + "/"
                + System.currentTimeMillis() + UVCCameraHelper.SUFFIX_JPEG;

        mCameraHelper.capturePicture(picPath, new AbstractUVCCameraHandler.OnCaptureListener() {
            @Override
            public void onCaptureResult(String path) {
                if (TextUtils.isEmpty(path)) {
                    return;
                }
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        allinfo.images.add(path);
                        Toast.makeText(USBCameraActivity.this, "保存到：" + path + "", Toast.LENGTH_SHORT).show();
//                        postToServer(path);
                    }
                });


            }

        });


        return false;
    }


    private void showResolutionListDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(USBCameraActivity.this);
        View rootView = LayoutInflater.from(USBCameraActivity.this).inflate(R.layout.layout_dialog_list, null);
        ListView listView = (ListView) rootView.findViewById(R.id.listview_dialog);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(USBCameraActivity.this, android.R.layout.simple_list_item_1, getResolutionList());
        if (adapter != null) {
            listView.setAdapter(adapter);
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (mCameraHelper == null || !mCameraHelper.isCameraOpened())
                    return;
                final String resolution = (String) adapterView.getItemAtPosition(position);
                String[] tmp = resolution.split("x");
                if (tmp != null && tmp.length >= 2) {
                    int widht = Integer.valueOf(tmp[0]);
                    int height = Integer.valueOf(tmp[1]);
                    mCameraHelper.updateResolution(widht, height);
                }
                mDialog.dismiss();
            }
        });

        builder.setView(rootView);
        mDialog = builder.create();
        mDialog.show();
    }

    // example: {640x480,320x240,etc}
    private List<String> getResolutionList() {
        List<Size> list = mCameraHelper.getSupportedPreviewSizes();
        List<String> resolutions = null;
        if (list != null && list.size() != 0) {
            resolutions = new ArrayList<>();
            for (Size size : list) {
                if (size != null) {
                    resolutions.add(size.width + "x" + size.height);
                }
            }
        }
        return resolutions;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtils.releaseFile();
        // step.4 release uvc camera resources
        if (mCameraHelper != null) {
            mCameraHelper.release();
        }
    }

    private void showShortMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public USBMonitor getUSBMonitor() {
        return mCameraHelper.getUSBMonitor();
    }

    @Override
    public void onDialogResult(boolean canceled) {
        if (canceled) {
            showShortMsg("取消操作");
        }
    }

    public boolean isCameraOpened() {
        return mCameraHelper.isCameraOpened();
    }

    @Override
    public void onSurfaceCreated(CameraViewInterface view, Surface surface) {
        if (!isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.startPreview(mUVCCameraView);
            isPreview = true;
        }
    }

    @Override
    public void onSurfaceChanged(CameraViewInterface view, Surface surface, int width, int height) {

    }

    @Override
    public void onSurfaceDestroy(CameraViewInterface view, Surface surface) {
        if (isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.stopPreview();
            isPreview = false;
        }
    }

    @OnClick({R.id.btn_user, R.id.btn_yes, R.id.btn_newPersion, R.id.btn_logout, R.id.btn_change})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_user: //根据手机号获取患者
                submitUser();
                break;
            case R.id.btn_yes:
                submitPersion();
                break;
            case R.id.btn_newPersion: //新建患者
                submitNewPersion();
                break;
            case R.id.btn_logout:
                finish();
                startActivity(new Intent(context, LoginActivity.class));
                break;
            case R.id.btn_change:
                allinfo.images.clear();
                llAdd.setVisibility(View.VISIBLE);
                llInfor.setVisibility(View.GONE);
                btnYes.setVisibility(View.GONE);
                rePutView();
                break;
        }
    }

    private void submitNewPersion() {
        String name = etNewName.getEditableText().toString();
        String phone = etNewPhone.getEditableText().toString();
        String id = etNewCode.getEditableText().toString();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(id)) {
            Toast.makeText(context, "填写内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (id.length() != 18) {
            Toast.makeText(context, "身份证填写错误", Toast.LENGTH_SHORT).show();
            return;
        }
        age.setText("患者年龄:"+getAgeByCertId(id));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", name);
            jsonObject.put("mobile", phone);
            if (Integer.parseInt(id.substring(16, 17)) % 2 == 0) {
                jsonObject.put("sex", 2);
                tvXingbie.setText("患者性别:女");
            } else {
                jsonObject.put("sex", 1);
                tvXingbie.setText("患者性别:男");
            }
            jsonObject.put("birthDate", id.substring(6, 10) + "-" + id.substring(10, 12) + "-" + id.substring(12, 14) + "");
            jsonObject.put("idCard", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ByteArrayEntity entity = null;
        Log.d("JSON", jsonObject.toString());
        try {
            entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String infox = (String) SPUtils.get(context, "userInfo", "");
        Gson gson = new Gson();
        LoginInfo info = gson.fromJson(infox, LoginInfo.class);

        HttpUtils.httpPostJsonMethod(USBCameraActivity.this, UrlContext.newPersion + info.getToken(), entity, "application/json", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("rs", response.toString());
                PersionBean persion = new Gson().fromJson(response.toString(), PersionBean.class);
                if (persion.isStatus()) {
                    allinfo.persionID = persion.getMsg();
                    Toast.makeText(context, "患者上传成功", Toast.LENGTH_SHORT).show();
//                            btnUser.setText(name);

                    huanzhe.setText("患者姓名:" + name);
                    tvphone.setText("患者电话:" + phone);

                    llAdd.setVisibility(View.GONE);
                    llInfor.setVisibility(View.VISIBLE);
                    btnYes.setVisibility(View.VISIBLE);

                    rePutView();
                } else {
                    Toast.makeText(context, persion.getMsg(), Toast.LENGTH_SHORT).show();
                    rePutView();
                }

            }


            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                rePutView();
            }
        });
    }

    /**
     * 根据患者手机号获取信息
     */
    private void submitUser() {


        String phone = etPhone.getEditableText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(context, "填写内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }


        ByteArrayEntity entity = null;

        try {

            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String infox = (String) SPUtils.get(context, "userInfo", "");
        Gson gson = new Gson();
        LoginInfo info = gson.fromJson(infox, LoginInfo.class);

        HttpUtils.httpGeTMethod(USBCameraActivity.this, UrlContext.HuanZhe + phone + "?" + "auth=" + info.getToken()
                , entity, "application/json", new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        Log.e("rs", response.toString());
                        GetPersonBean persion = new Gson().fromJson(response.toString(), GetPersonBean.class);
                        if (persion.isStatus()) {
                            allinfo.persionID = persion.getData().getId();
                            huanzhe.setText("患者姓名:" + persion.getData().getName());
                            tvphone.setText("患者电话:" + persion.getData().getMobile());
                            age.setText("患者年龄:" + persion.getData().getAge());
                            tvXingbie.setText("患者性别:" + (persion.getData().getSex() == 2 ? "女" : "男"));
                            llAdd.setVisibility(View.GONE);
                            llInfor.setVisibility(View.VISIBLE);
                            btnYes.setVisibility(View.VISIBLE);
                            rePutView();
                        } else {
                            Toast.makeText(context, "信息不匹配，需新建病例", Toast.LENGTH_SHORT).show();
                            rePutView();
                        }

                    }


                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        super.onFailure(statusCode, headers, throwable, errorResponse);
                        rePutView();
                    }


                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 111){
            rePutView();
        }
    }

    /**
     * 提交病例
     */
    private void submitPersion() {
        if (TextUtils.isEmpty(allinfo.persionID)) {
            Toast.makeText(context, "请选择患者", Toast.LENGTH_SHORT).show();
            return;
        }
        if (allinfo.images.size() == 0) {
            Toast.makeText(context, "暂未拍照和录像", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(context, SubmitActivity.class);
        intent.putExtra("info", allinfo);
        startActivityForResult(intent,111);

    }



    /**
     * 根据身份证号获取年龄
     *
     * @param certId
     * @return
     */
    public static String getAgeByCertId(String certId) {
        String birthday = "";
        if (certId.length() == 18) {
            birthday = certId.substring(6, 10) + "/"
                    + certId.substring(10, 12) + "/"
                    + certId.substring(12, 14);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date now = new Date();
        Date birth = new Date();
        try {
            birth = sdf.parse(birthday);
        } catch (ParseException e) {
        }
        long intervalMilli = now.getTime() - birth.getTime();
        int age = (int) (intervalMilli / (24 * 60 * 60 * 1000)) / 365;
        System.out.println(age);
        return age + "";
    }
    //重启界面
    private void rePutView(){
        mCameraHelper.stopPreview();
        mCameraHelper.startPreview(mUVCCameraView);
    }
}
